import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../themes/expense_theme.dart';

/// 增强的日期时间选择器
class EnhancedDatePicker extends StatefulWidget {
  final DateTime initialDate;
  final DateTime? firstDate;
  final DateTime? lastDate;
  final Function(DateTime) onDateSelected;
  final String? title;
  final bool showTime;
  final bool showQuickOptions;

  const EnhancedDatePicker({
    super.key,
    required this.initialDate,
    required this.onDateSelected,
    this.firstDate,
    this.lastDate,
    this.title,
    this.showTime = true,
    this.showQuickOptions = true,
  });

  @override
  State<EnhancedDatePicker> createState() => _EnhancedDatePickerState();
}

class _EnhancedDatePickerState extends State<EnhancedDatePicker>
    with SingleTickerProviderStateMixin {
  late DateTime _selectedDate;
  late TimeOfDay _selectedTime;
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _selectedDate = widget.initialDate;
    _selectedTime = TimeOfDay.fromDateTime(widget.initialDate);
    
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOutCubic,
    ));
    
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: SlideTransition(
          position: _slideAnimation,
          child: Container(
            constraints: BoxConstraints(
              maxWidth: 400.w,
              maxHeight: 600.h,
            ),
            decoration: BoxDecoration(
              color: ExpenseTheme.cardBackground,
              borderRadius: BorderRadius.circular(20.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildHeader(),
                if (widget.showQuickOptions) _buildQuickOptions(),
                _buildDatePicker(),
                if (widget.showTime) _buildTimePicker(),
                _buildActions(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        gradient: ExpenseTheme.primaryGradient,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.calendar_today,
            color: Colors.white,
            size: 24.sp,
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Text(
              widget.title ?? '选择日期时间',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
          IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: Icon(
              Icons.close,
              color: Colors.white,
              size: 20.sp,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建快速选择选项
  Widget _buildQuickOptions() {
    final now = DateTime.now();
    final quickOptions = [
      {'label': '今天', 'date': now},
      {'label': '昨天', 'date': now.subtract(const Duration(days: 1))},
      {'label': '本周一', 'date': now.subtract(Duration(days: now.weekday - 1))},
      {'label': '上周一', 'date': now.subtract(Duration(days: now.weekday + 6))},
    ];

    return Container(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '快速选择',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: ExpenseTheme.textSecondary,
            ),
          ),
          SizedBox(height: 8.h),
          Wrap(
            spacing: 8.w,
            runSpacing: 8.h,
            children: quickOptions.map((option) {
              final date = option['date'] as DateTime;
              final isSelected = _isSameDay(date, _selectedDate);
              
              return InkWell(
                onTap: () {
                  setState(() {
                    _selectedDate = date;
                  });
                },
                borderRadius: BorderRadius.circular(20.r),
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                  decoration: BoxDecoration(
                    color: isSelected 
                        ? ExpenseTheme.primaryBlue.withValues(alpha: 0.1)
                        : ExpenseTheme.softBlue,
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(
                      color: isSelected 
                          ? ExpenseTheme.primaryBlue 
                          : ExpenseTheme.lightBlue,
                      width: isSelected ? 2 : 1,
                    ),
                  ),
                  child: Text(
                    option['label'] as String,
                    style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                      color: isSelected 
                          ? ExpenseTheme.primaryBlue 
                          : ExpenseTheme.textPrimary,
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 构建日期选择器
  Widget _buildDatePicker() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '选择日期',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: ExpenseTheme.textSecondary,
            ),
          ),
          SizedBox(height: 8.h),
          InkWell(
            onTap: _showDatePicker,
            borderRadius: BorderRadius.circular(12.r),
            child: Container(
              width: double.infinity,
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: ExpenseTheme.softBlue,
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(color: ExpenseTheme.lightBlue),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.date_range,
                    color: ExpenseTheme.primaryBlue,
                    size: 20.sp,
                  ),
                  SizedBox(width: 12.w),
                  Text(
                    DateFormat('yyyy年MM月dd日', 'zh_CN').format(_selectedDate),
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: ExpenseTheme.textPrimary,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const Spacer(),
                  Icon(
                    Icons.arrow_forward_ios,
                    color: ExpenseTheme.textSecondary,
                    size: 16.sp,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建时间选择器
  Widget _buildTimePicker() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '选择时间',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: ExpenseTheme.textSecondary,
            ),
          ),
          SizedBox(height: 8.h),
          InkWell(
            onTap: _showTimePicker,
            borderRadius: BorderRadius.circular(12.r),
            child: Container(
              width: double.infinity,
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: ExpenseTheme.softBlue,
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(color: ExpenseTheme.lightBlue),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.access_time,
                    color: ExpenseTheme.primaryBlue,
                    size: 20.sp,
                  ),
                  SizedBox(width: 12.w),
                  Text(
                    _selectedTime.format(context),
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: ExpenseTheme.textPrimary,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const Spacer(),
                  Icon(
                    Icons.arrow_forward_ios,
                    color: ExpenseTheme.textSecondary,
                    size: 16.sp,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActions() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          Expanded(
            child: TextButton(
              onPressed: () => Navigator.of(context).pop(),
              style: TextButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                '取消',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: ExpenseTheme.textSecondary,
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: ElevatedButton(
              onPressed: _confirmSelection,
              style: ElevatedButton.styleFrom(
                backgroundColor: ExpenseTheme.primaryBlue,
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                '确定',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示日期选择器
  Future<void> _showDatePicker() async {
    final date = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: widget.firstDate ?? DateTime(2020),
      lastDate: widget.lastDate ?? DateTime.now().add(const Duration(days: 365)),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: Theme.of(context).colorScheme.copyWith(
              primary: ExpenseTheme.primaryBlue,
              onPrimary: Colors.white,
              surface: ExpenseTheme.cardBackground,
              onSurface: ExpenseTheme.textPrimary,
            ),
          ),
          child: child!,
        );
      },
    );

    if (date != null) {
      setState(() {
        _selectedDate = date;
      });
    }
  }

  /// 显示时间选择器
  Future<void> _showTimePicker() async {
    final time = await showTimePicker(
      context: context,
      initialTime: _selectedTime,
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: Theme.of(context).colorScheme.copyWith(
              primary: ExpenseTheme.primaryBlue,
              onPrimary: Colors.white,
              surface: ExpenseTheme.cardBackground,
              onSurface: ExpenseTheme.textPrimary,
            ),
          ),
          child: child!,
        );
      },
    );

    if (time != null) {
      setState(() {
        _selectedTime = time;
      });
    }
  }

  /// 确认选择
  void _confirmSelection() {
    final finalDateTime = DateTime(
      _selectedDate.year,
      _selectedDate.month,
      _selectedDate.day,
      widget.showTime ? _selectedTime.hour : _selectedDate.hour,
      widget.showTime ? _selectedTime.minute : _selectedDate.minute,
    );
    
    widget.onDateSelected(finalDateTime);
    Navigator.of(context).pop();
  }

  /// 判断是否是同一天
  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
           date1.month == date2.month &&
           date1.day == date2.day;
  }
}

/// 显示增强的日期选择器
Future<DateTime?> showEnhancedDatePicker({
  required BuildContext context,
  required DateTime initialDate,
  DateTime? firstDate,
  DateTime? lastDate,
  String? title,
  bool showTime = true,
  bool showQuickOptions = true,
}) async {
  DateTime? selectedDate;
  
  await showDialog<DateTime>(
    context: context,
    barrierDismissible: true,
    builder: (context) => EnhancedDatePicker(
      initialDate: initialDate,
      firstDate: firstDate,
      lastDate: lastDate,
      title: title,
      showTime: showTime,
      showQuickOptions: showQuickOptions,
      onDateSelected: (date) {
        selectedDate = date;
      },
    ),
  );
  
  return selectedDate;
}
